package test.my.com.myapplicationtest.write_view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import java.io.File;

/**
 * Created by ThinkPad on 2016/3/14.
 */
public class NewImageView extends View {

    private Paint mPaint;
    private Canvas mCanvas;
    private Path mPath;
    private Bitmap mBitmap;
    private Bitmap mBitmap2;

    public NewImageView(Context context) {
        super(context);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int windowWidth = wm.getDefaultDisplay().getWidth();
        int windowHeight = wm.getDefaultDisplay().getHeight();
        mPaint = new Paint();
        String resPath = Environment.getExternalStorageDirectory() + File.separator + "170.jpg";
//        String resPath = Environment.getExternalStorageDirectory() + File.separator + "banner.png";
        mBitmap = BitmapFactory.decodeFile(resPath).copy(Bitmap.Config.ARGB_8888, true);
        mBitmap2 = resizeBitmap(mBitmap, windowWidth, windowHeight);
    }

    public Bitmap resizeBitmap(Bitmap bitmap, int w, int h) {
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int newWidth = w;
            int newHeight = h;
            float scaleWight = (float) newWidth / width;
            float scaleHeight = (float) newHeight / height;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleHeight, scaleHeight);
            Bitmap res = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            return res;

        } else {
            return null;
        }
    }

    public NewImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NewImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(mBitmap2, 0, 0, mPaint);
    }
}
